//
//  CNComposeViewController.swift
//  Ccweibo
//
//  Created by 陈锦聪 on 16/3/30.
//  Copyright © 2016年 Coco. All rights reserved.
//

import UIKit
import SVProgressHUD
import SnapKit

class CNComposeViewController: UIViewController {
    
    var PSBottomConstraint: Constraint?

    override func viewDidLoad() {
        super.viewDidLoad()
        prepareUI()
    }
    override func viewDidAppear(animated: Bool) {
        super.viewWillAppear(animated)
        if PSBottomConstraint == nil {
            textView.becomeFirstResponder()
        }
    }
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    private func prepareUI() {
        view.backgroundColor = UIColor.whiteColor()
        setupNavigationBar()
        // textView必须是view的第一个子view才能自动调整适应NavigationBar
        setupTextView()
        setupPhotoSeletor()
        setupToolBar()
        setupTipLabel()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    func keyboardWillChangeFrame(notification: NSNotification) {
        let interval = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey]! as! NSTimeInterval
        let endRect = notification.userInfo?[UIKeyboardFrameEndUserInfoKey]!.CGRectValue ?? CGRectZero
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(-(UIScreen.height - endRect.origin.y))
        }
        UIView.animateWithDuration(interval) { () -> Void in
            self.toolBar.layoutIfNeeded()
        }
    }
    @objc private func pictureAction() {
        textView.resignFirstResponder()
        photoSeletor.view.snp_updateConstraints { (make) -> Void in
            PSBottomConstraint = make.bottom.equalTo(view).constraint
        }
        UIView.animateWithDuration(defaultDuration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    @objc private func trendAction() {
        CNPrint(item: __FUNCTION__)
    }
    @objc private func mentionAction() {
        CNPrint(item: __FUNCTION__)
    }
    @objc private func emoticonAction() {
        textView.resignFirstResponder()
        textView.inputView = textView.inputView == nil ? emoticonKeyboard : nil
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            self.textView.becomeFirstResponder()
        })
    }
    @objc private func addAction() {
        CNPrint(item: __FUNCTION__)
    }
    private func setupToolBar() {
        view.addSubview(toolBar)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        let itemSettings = [
            ["imageName": "compose_toolbar_picture", "action": "pictureAction"],
            ["imageName": "compose_trendbutton_background", "action": "trendAction"],
            ["imageName": "compose_mentionbutton_background", "action": "mentionAction"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticonAction"],
            ["imageName": "compose_add_background", "action": "addAction"]]
        // items先创建再使用
        toolBar.items = [UIBarButtonItem]()
        var index = 0
        for dict in itemSettings {
            let imageName = dict["imageName"]!
            let action = dict["action"]!
            let item = UIBarButtonItem(image: UIImage(named: imageName), style: UIBarButtonItemStyle.Plain, target: self, action: Selector(action))
            toolBar.items?.append(item)
            if index < itemSettings.count - 1 {
                toolBar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            }
            index++
        }
    }
    private func setupTextView() {
        view.addSubview(textView)
        // 自动调整导航栏下的view向下偏移64
        automaticallyAdjustsScrollViewInsets = true
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
    }
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "dismissAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发表", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatusAction")
        navigationItem.rightBarButtonItem?.enabled = false
        setupTitleView()
    }
    private func setupTitleView() {
        let prefix = "发微博"
        if let userName = CNUserAccountViewModel.sharedInstance.userAccount?.screen_name {
            let text = prefix + "\n" + userName
            let label = UILabel()
            label.textColor = UIColor.blackColor()
            label.font = UIFont.systemFontOfSize(13)
            label.textAlignment = NSTextAlignment.Center
            label.numberOfLines = 0
            // 属性文本
            let attr = NSMutableAttributedString(string: text)
            let nameRange = (text as NSString).rangeOfString(userName)
            attr.addAttributes([NSForegroundColorAttributeName : UIColor.lightGrayColor(), NSFontAttributeName : UIFont.systemFontOfSize(11)], range: nameRange)
            label.attributedText = attr
            // 注意: 必须在设置属性文本之后调用
            label.sizeToFit()
            navigationItem.titleView = label
        } else {
            navigationItem.title = prefix
        }
    }
    private func setupTipLabel() {
        view.addSubview(tipLabel)
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(view).offset(-3)
            make.bottom.equalTo(toolBar.snp_top).offset(-3)
        }
    }
    private func setupPhotoSeletor() {
        view.addSubview(photoSeletor.view)
        // 响应者链条
        addChildViewController(photoSeletor)
        photoSeletor.view.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.equalTo(view)
            make.height.equalTo(view).multipliedBy(0.6)
            make.bottom.equalTo(view).offset(UIScreen.height * 0.6)
        }
    }
    @objc private func dismissAction() {
        SVProgressHUD.dismiss()
        textView.resignFirstResponder()        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func sendStatusAction() {
        let status = textView.emoticonsText()
        let image = photoSeletor.photos.first
        if status.characters.count > statusMaxCount {
            SVProgressHUD.showErrorWithStatus("微博内容超过限定长度", maskType: SVProgressHUDMaskType.Black)
            return
        }
        SVProgressHUD.showWithStatus("正在发布微博...", maskType: SVProgressHUDMaskType.Gradient)
        CNStatusViewModel.sharedInstance.sendStatus(status, image: image) { (error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发布微博失败", maskType: SVProgressHUDMaskType.Black)
                CNPrint(item: "sendStatusAction: \(error)")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发布微博成功", maskType: SVProgressHUDMaskType.Clear)
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(500 * USEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                self.dismissAction()
            })
        }
    }
    private lazy var textView: CNComposeTextView = {
        let textView = CNComposeTextView()
        textView.font = UIFont.systemFontOfSize(18)
        textView.textColor = UIColor.blackColor()
        // textView可以垂直拖拽
        textView.alwaysBounceVertical = true
        // 拖拽时隐藏键盘(使用会有错误信息,忽略!)
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        textView.placeText = "分享新鲜事..."
        textView.delegate = self
        return textView
    }()
    private lazy var toolBar: UIToolbar = UIToolbar()
    /// 表情键盘
    private lazy var emoticonKeyboard: CNEmoKeyboardView = {
        let keyboard = CNEmoKeyboardView()
        keyboard.textView = self.textView
        return keyboard
    }()
    /// 字数提醒
    private lazy var tipLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.text = "\(statusMaxCount)"
        label.textColor = UIColor.lightGrayColor()
        return label
    }()
    /// 照片选择器
    private lazy var photoSeletor: CNPhotoSeletorController = CNPhotoSeletorController()
}

extension CNComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        let text = textView.emoticonsText()
        let count = statusMaxCount - text.characters.count
        tipLabel.text = "\(count)"
        tipLabel.textColor = count < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
